//
//  YALoginController.swift
//  KeepCliming
//
//  Created by 鱼龙之梦 on 15/9/2.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit
import SVProgressHUD
class YALoginController: UIViewController,UIWebViewDelegate {
    //MARK: - 用webView控件 用变量
    private lazy var webView = UIWebView()
    override func loadView() {
        view = webView
        webView.scalesPageToFit = true
        webView.delegate = self
        let label = UILabel()
        label.text = "登录新浪微博"
        label.textColor = UIColor.grayColor()
        label.sizeToFit()
        navigationItem.titleView = label
        //改变标题的颜色
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")//注意:传参数时加个冒号
    }
       //MARK: - 自动填充密码和用户名 就是执行js
    @objc private func autoFill (){
        let js = "document.getElementById('userId').value = '13391316157';" + "document.getElementsByClassName('input_note')[0].style.display='none';" +
            "document.getElementById('passwd').value ='20101204074';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.loadRequest(NSURLRequest(URL: YANetworking.sharedTools.URLForGETOAuthCode))
    }
    //MARK: - shouldStartLoadWithRequest 返回true继续加载，false 停止加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //判断请求地址的绝对地址的前半部分是否是回调地址
        let absoluteURLString = request.URL?.absoluteString
        if (absoluteURLString?.hasPrefix(YANetworking.sharedTools.redirect_uri) != true){
            return true//
        }
        //否 判断回调地址里是否含有code =
        //print("request.URL?.query\(request.URL?.query)")
        if let query = request.URL?.query where query.hasPrefix("code="){
            let code = query.substringFromIndex("code=".endIndex)
            //loadAceessToken(code)
            //这里用了MVVM模式
            YAUserAcountVM.sharedUserAccount.loadUserAccountFromVM(code).subscribeError({ (error) -> Void in
                printLog(error, logError: true)
                
                }, completed: { () -> Void in
                   //self.close(isAnimatioin: false)
                   SVProgressHUD.dismiss()
                   self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    NSNotificationCenter.defaultCenter().postNotificationName(YARootViewControllerSwitchNotification, object: self)
                   })
                   
            })
            //是 去请求网络
        }else{
           print("请求失败")
        }
        return false
    }
    
    //MARK: - 关闭登录页面
    func close() {
        SVProgressHUD.dismiss()//加载消失
        dismissViewControllerAnimated(true, completion: nil)
    }
    //网络出错处理
    private func netError(){
        SVProgressHUD.showInfoWithStatus("您的网路不给力")
        //延迟一段时间再关闭
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1*NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) { () -> Void in
            self.close()
        }
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //MARK:--- 下面两个方法已经整合到MVVM
    //获取用户信息
    private func loadUserInfo(account:YAUserAcount){
        YANetworking.sharedTools.loadUserInfoFromToos(account.uid!).subscribeNext({ (result) -> Void in
            let dict = result as! [NSString:AnyObject]
            account.name = dict["name"] as?String
            account.avatar_large = dict["avatar_large"] as?String
            account.saveUserAcount()
            }) { () -> Void in
                //
        }
    }
    //获取请求码
    private func loadAceessToken(coder:String){
     YANetworking.sharedTools.loadAccessTokenWithCode(coder).subscribeNext({ (result) -> Void in
        let account = YAUserAcount(dict: result as! [String:AnyObject])
       //这个时候的用户信息是不全的！
        self.loadUserInfo(account)
        }, error: {
            (error) ->Void in print(error)
     })
    }
}
